package com.bjsxt.controller;

import com.bjsxt.pojo.Employee;
import com.bjsxt.pojo.Expense;
import com.bjsxt.pojo.ExpenseItem;
import com.bjsxt.service.ExpenseService;
import com.bjsxt.service.impl.ExpenseServiceImpl;
import com.google.gson.GsonBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/sxt/ExpenseServlet")
public class ExpenseServlet extends  BaseServlet {

    private ExpenseService  expenseService=new ExpenseServiceImpl();

    //待审报销查询事项
    protected void  expenseFindMore(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Employee emp = (Employee) req.getSession().getAttribute("emp");

        List<Expense> list = expenseService.findMore(emp.getEmpId());

        String json = new GsonBuilder().setDateFormat("yyyy-MM-dd").create().toJson(list);

        resp.getWriter().print(json);

    }



        //添加报销单实现
    protected void  expenseSave(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /*********接受报销单数据*******************/
        double totalAmount = Double.parseDouble(req.getParameter("totalAmount"));
        String nextAuditor = req.getParameter("nextAuditor");
        String expDesc = req.getParameter("expDesc");
        Employee emp = (Employee) req.getSession().getAttribute("emp");
        java.sql.Date expTime = new java.sql.Date(new Date().getTime());
        Expense  expense=new  Expense(emp.getEmpId(),  totalAmount, expTime,  expDesc,  nextAuditor);

        /*********接受报销单明细*******************/
        //[通信费用,通信费用]
        String[] types = req.getParameterValues("type");
        //[1000,4000]
        String[] amounts = req.getParameterValues("amount");
        String[] itemDescs = req.getParameterValues("itemDesc");

        List<ExpenseItem>  list=new ArrayList<>();
        for (int i = 0; i <types.length ; i++) {

            String type = types[i];
            Double amount =Double.parseDouble(amounts[i]);
            String itemDesc = itemDescs[i];

            ExpenseItem  expenseItem=new ExpenseItem(type,amount,itemDesc);
            list.add(expenseItem);

        }

        int save = expenseService.save(expense,list);

        resp.getWriter().print(save);


    }
}
